package cn.edu.hnu.gpg.handler;

import cn.edu.hnu.gpg.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 网页全局拦截器，验证登录信息
 */
public class AuthCheckInterceptor implements HandlerInterceptor {

    private static final String LOGIN = "/login";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        // TODO: 根据请求 header 中的 User-Agent 判断请求来自 Web 或是 App 分开验证

        // 浏览器访问时登录信息验证
        if (request.getSession(false) == null) {
            response.sendRedirect(LOGIN);
        } else {
            User user = ((User) request.getSession().getAttribute("user"));
            if (user == null)
                response.sendRedirect(LOGIN);
            else
                return true;
        }

        return false;
    }
}
